<script lang="ts" setup>
import pageVue from "/src/lib/lay/page.vue";
import control from "/src/lib/action/control.vue";
import { ref, reactive } from "@vue/runtime-core";
import { $ } from "../../../../lib/request";
import { modal } from "vxe-table";
import { IDCardNumber, CarId, isNull, phone, Number } from '/src/lib/encrypt/editRules.ts'
const itemsl = ["删除", "确认派单", "派车反馈"];
const priceList = {} as any;
const Pagechildren = [{ name: "top" }];
let Data = ref([] as Array<any>);

// 反正以后要大改，就先不写到状态里了 初始的数值
const itemData = ref({
  精品级配砂: 0,
  精品瓜子片: 0,
  精品二分石: 0,
  精品三分石: 0,
  石粉: 0,
  瓜子片: 0,
  三分石: 0,
  机制砂: 0,
  泥饼: 0,
  粉末: 0,
} as any),
  isEdit = ref(false);

// 删除对象空属性
const removeEmpty = (obj: any) => {
  Object.keys(obj).forEach((key) => {
    !obj[key] && obj[key] != 0 && delete obj[key];
  });
  return obj;
};

// 初始化空对象
const initEmpty = (obj: object, init: number) => {
  Object.keys(obj).forEach((key) => {
    obj[key] !== init && !obj[key] && (obj[key] = init);
  });
  return obj;
};
//contol确认修改
const setItem = () => {
  $.get("oa/saas/product/ylxg.do", {
    params: { ...itemData.value },
  }).then((respose) => {
    // console.log(respose);
    isEdit.value = false;
    modal.message({ content: respose.data.message, status: "success" });
  });

};

//图表一配置项
const gridOptions = reactive({
  border: true,
  resizable: false,
  height: 330,
  rowId: "id",
  checkboxConfig: {
    reserve: true,
  },
  pagerConfig: {
    pageSize: 10,
  },
  editConfig: { trigger: "click", mode: "row", enabled: true },
  editRules: {
    "carCard": CarId,
    "idCard": IDCardNumber,
    "productName": isNull,
    "name": isNull,
    "phone": phone,
    "driverName": isNull,
    "truck": Number,
  },
  columns: [
    {
      type: "checkbox",
      width: 50,
    },
    { field: "khmc", title: "客户名称", editRender: { name: "$input" } },
    { field: "carCard", title: "车牌号", editRender: { name: "$input" } },
    {
      field: "productName",
      title: "物料名称",
      editRender: {
        name: "$select",
        options: [
          { value: "精品级配砂", label: "精品级配砂" },
          { value: "精品瓜子片", label: "精品瓜子片" },
          { value: "精品二分石", label: "精品二分石" },
          { value: "精品三分石", label: "精品三分石" },
          { value: "石粉", label: "石粉" },
          { value: "瓜子片", label: "瓜子片" },
          { value: "三分石", label: "三分石" },
          { value: "机制砂", label: "机制砂" },
          { value: "泥饼", label: "泥饼" },
          { value: "粉末", label: "粉末" },
        ],
      },
    },
    {
      field: "truck",
      title: "重量(吨)",
      showOverflow: true,
      editRender: { name: "$input" },
    },
    {
      field: "price",
      title: "单价",
      showOverflow: true,
      editRender: { name: "$input" },
    },
    {
      field: "driverName",
      title: "司机姓名",
      showOverflow: true,
      editRender: { name: "$input" },
    },
    {
      field: "phone",
      title: "手机号",
      showOverflow: true,
      editRender: { name: "$input" },
    },
    {
      field: "idCard",
      title: "身份证号码",
      showOverflow: true,
      editRender: { name: "$input" },
    },
  ],
  proxyConfig: {
    seq: true, // 启用动态序号代理（分页之后索引自动计算为当前页的起始序号）
    props: {
      result: "result",
      total: "page.total",
    },
    ajax: {
      // 接收 Promise
      query: ({
        page: { currentPage, pageSize },
      }: {
        page: {
          currentPage: number;
          pageSize: number;
        };
      }) => {
        return new Promise((resolve) => {
          let list = [] as any[];

          list = [{

          }]
          resolve({
            page: {
              total: list.length,
            },
            result: list.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            ),
          });
        });
      },
    },
  },
});


const xTable = ref({} as any);

const getItemPrice = ({ khmc, ...item }: any) => {
  const thisPrice = priceList[khmc];
  console.log('價格表', priceList, thisPrice);

  let total = 0;
  const priceChar = {

    "精品瓜子片": 'jpgzpdj',
    "精品级配砂": 'jpjpsdj',
    "精品二分石": 'jpefsdj',
    "精品三分石": 'jpsfsdj',
    "机制砂": 'jzsdj',
    "石粉": 'sfdj',
    "瓜子片": 'gzpdj',
    "三分石": 'sfsdj',
    "粉末": 'fmdj',
    "泥饼": 'nbdj',
  }
  Object.keys(item).forEach((key) => {
    // console.log();

    total += thisPrice[priceChar[key]] * item[key] || 0
  })

  return total
}
//确认派单 
const handlePaidan = () => {
  // const $table = yTable.value; 原本
  const $table = xTable.value;

  const selectRecords = $table.getCheckboxRecords();
  const addList = [] as any[]
  selectRecords.forEach(({ id, ...item }: any) => {
    // console.log(...item);
    console.log(addList);
    
    addList.push(initEmpty({...item,}, 0))
  });

  if(addList.length>0){
  console.log('临时派车参数',JSON.stringify(addList).replace(/^\[+|\]+$/g, ''));

  $.get("oa/saas/core/productcar/temporaryCustomer.do", {
    params: {
      addCarList: JSON.stringify(addList).replace(/^\[+|\]+$/g, '')

    }
  }).then((respose) => {

    modal.message({ content: respose.data.message, status: "success" });
    $table.removeCheckboxRow()
    name()
  });
  }else{
       modal.message({ content:'请勾选行并完善信息', status: "error" });
    }
};
//新增一行
 const insertEvent = async (row: any) => {
              const $table = xTable.value
              const record = {}
              const { row: newRow } = await $table.insertAt(record, row)
              await $table.setActiveCell(newRow, 'khmc')
            }

//给contol组件赋值
name()
function name() {
  console.log('diaoyongleyici');
  
$.get("oa/saas/product/ylyc.do", { params: {}, }).then((data) => {
  var arr = data.data.data.ylyc
  const mockData = {
    精品级配砂: 0,
    精品瓜子片: 0,
    精品二分石: 0,
    精品三分石: 0,
    石粉: 0,
    瓜子片: 0,
    三分石: 0,
    机制砂: 0,
    泥饼: 0,
    粉末: 0,
  };
  arr.forEach(({ productForeast, productName }: any) => {
    mockData[productName] = productForeast
  });
  // console.log(mockData);
  itemData.value = initEmpty({ ...mockData }, 0);
});
}
</script>

<template lang="pug">
pageVue(:children='Pagechildren')
  template(v-slot:top)
    .hjk
      .topp 临时客户派车
      control(:itemData="itemData" :isEdit="isEdit")
        template(v-slot:title)
          .title 余量预测
      div(style="display: flex;justify-content: center")
        vxe-button.bott(@click="isEdit = !isEdit" style="margin-right: 67px;") {{ isEdit ? '取消修改' : '修改余量' }}
        vxe-button.bott(v-if="isEdit" @click="setItem") 确认修改
      vxe-grid(v-bind="gridOptions"   ref="xTable" highlight-hover-row  )
      .bot
        vxe-button.bott( style="margin-right: 68px;"  @click="insertEvent(0)") 新增一行
        vxe-button.bott(style="margin-right: 68px;"   @click="xTable.removeCheckboxRow()" ) 删除
        vxe-button.bott(style="margin-right: 68px;"  @click="handlePaidan" ) 确认派单
      
</template>
<style lang="scss" scoped>
.hjk {
  display: grid;
  gap: 20px;
  padding: 48px;
  height: 968px;
}
.topp {
  font-size: 20px;
  font-weight: bold;
  line-height: 20px;
  color: #5d5d5d;
}
.headerr {
  width: 86%;
  margin: 20px auto;
  font-size: 18px;
  font-family: Source Han Sans CN;
  line-height: 36px;
  color: #000000;
  background: #f0faf2;
  border-radius: 10px;
  padding: 20px;
  .text {
    margin-left: 40px;
  }
}
.mid {
  font-size: 18px;
  color: #5d5d5d;
  font-weight: bold;
}
.bot {
  // display: flex;
  text-align: center;
  margin-bottom: -20px;
  padding: 0 5px;
}
.bott {
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  // width: 94px;
  height: 34px;
  background: #f0faf2;
  box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.16);
  border-radius: 10px;
  font-size: 18px;
  line-height: 34px;
  color: #5d5d5d;
  border: none;
}
</style>
